package com.android.tvservicer

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.IBinder
import android.util.Log
import android.widget.ArrayAdapter
import java.io.IOException
import java.net.*
import java.util.*
import javax.jmdns.JmDNS
import javax.jmdns.ServiceInfo
import javax.jmdns.ServiceListener


/**
 * Created by mr.kong on 2017/9/25.
 */
class RegisterBoardDeviceServer : Service() {
    lateinit var serviceInfo: ServiceInfo
    var jmDNS: JmDNS? = null
    var listener: ServiceListener? = null
    lateinit var wifi: WifiManager
    lateinit var lock: WifiManager.MulticastLock
    val TAG = MainActivity::class.java.simpleName
    private val type = "_kerust._tcp.local."//_airplay._tcp.local.
    //Samsung-Galaxy-S7-edge-lan.local.
    //_raop._tcp.local.
    var mList: MutableList<String>? = null
    lateinit var adapter: ArrayAdapter<String>
    private var id: String? = null
    private var name: String? = null

    override fun onBind(p0: Intent?): IBinder {
        throw UnsupportedOperationException("Not yet implemented")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        registerBoardDeviceService()
        return super.onStartCommand(intent, flags, startId)
    }

    private fun registerBoardDeviceService() {
        Thread(object : Runnable {
            @SuppressLint("WifiManagerLeak")
            override fun run() {
                val deviceIdFromDisk = BoardDeviceUtils.getDeviceIdFromDisk()
                wifi = getSystemService(Context.WIFI_SERVICE) as WifiManager
                lock = wifi.createMulticastLock(javaClass.simpleName)
                lock.setReferenceCounted(true)
                try {
                    val localIpAddress = getLocalIpAddress()

                    if (!localIpAddress.toString().contains("0.0.0")) {
                        lock.acquire()
                        jmDNS = JmDNS.create(localIpAddress)
                        if (deviceIdFromDisk != null) {
                            val list = deviceIdFromDisk.split("&")
                            Log.e(TAG, list[0] + "" + list[1])
                            id = list[0]
                            name = list[1]
                        }
                        /**
                         * 注册设备的服务类型
                         */
                        serviceInfo = ServiceInfo.create(type,
                                deviceIdFromDisk, 7433,
                                name)
                        serviceInfo.setText(getDeviceDetailsMap())
                        jmDNS?.registerService(serviceInfo)
                    }

                    val localIp = getLocalIp()

                    if (!localIp.contains("0.0.0")) {

                        lock.acquire()
                        jmDNS = JmDNS.create(localIp)
                        if (deviceIdFromDisk != null) {
                            val list = deviceIdFromDisk.split("&")
                            Log.e(TAG, list[0] + "" + list[1])
                            id = list[0]
                            name = list[1]
                        }
                        /**
                         * 注册设备的服务类型
                         */
                        serviceInfo = ServiceInfo.create(type,
                                deviceIdFromDisk, 7433,
                                name)
                        serviceInfo.setText(getDeviceDetailsMap())
                        jmDNS?.registerService(serviceInfo)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                    return
                }
            }
        }).start()
    }

    private fun getDeviceDetailsMap(): Map<String, String> {
        val info = HashMap<String, String>()
        info.put("device_name", "my_device_name")
        return info
    }

    private fun getLocalIpAddress(): InetAddress {
        @SuppressLint("WifiManagerLeak") val wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager
        val connectionInfo = wifiManager.connectionInfo
        val ipAddress = connectionInfo.ipAddress
        var address: InetAddress? = null
        try {
            address = InetAddress.getByName(String.format(Locale.ENGLISH, "%d.%d.%d.%d", ipAddress and 0xff,
                    ipAddress shr 8 and 0xff, ipAddress shr 16 and 0xff, ipAddress shr 24 and 0xff))
        } catch (e: UnknownHostException) {
            e.printStackTrace()
        }
        return address!!
    }

    private fun getLocalIp(): String {

        try {
            // 获取本地设备的所有网络接口
            val enumerationNi = NetworkInterface
                    .getNetworkInterfaces()
            while (enumerationNi.hasMoreElements()) {
                val networkInterface = enumerationNi.nextElement()
                val interfaceName = networkInterface.getDisplayName()

                // 如果是有限网卡
                if (interfaceName == "eth0") {
                    val enumIpAddr = networkInterface
                            .getInetAddresses()
                    while (enumIpAddr.hasMoreElements()) {
                        // 返回枚举集合中的下一个IP地址信息
                        val inetAddress = enumIpAddr.nextElement()
                        // 不是回环地址，并且是ipv4的地址
                        if (!inetAddress.isLoopbackAddress() && inetAddress is Inet4Address) {
                            return inetAddress.getHostAddress()
                        }
                    }
                } else {
                    return getLocalIpAddress().toString()
                }

            }

        } catch (e: SocketException) {
            e.printStackTrace()
        }

        return ""

    }


}